

[1,2,[1,2,[25,7],23,2],45,[2,3]]

class BinaryTree
  attr_accessor :element, :left, :right

  def initialize(element,left,right)
    self.element = element
    self.left = left
    self.right = right
  end

  def to_s
    left_to_s = left ?  left.to_s : nil
    right_to_s = right ?  right.to_s : nil
    "(#{left_to_s} ,#{element}, #{right_to_s})"
  end
end

bt = BinaryTree.new(2,
      BinaryTree.new(1,
       BinaryTree.new(0,nil,nil),nil),
      BinaryTree.new(4,
       BinaryTree.new(3,nil,nil),
       BinaryTree.new(5,nil,nil)))

#puts bt.to_s

class BinaryTree
  def is_complete_tree?
    next_children = [self]
    i = 0
    while !next_children.empty?
      number_of_children = next_children.length
      next_children = next_children.inject([]) do |result, binary_tree|
        [:left,:right].each {|child| result << binary_tree.send(child) if binary_tree.send(child)}; result        
      end
      return false if number_of_children != (2**i) && !next_children.empty?
      i += 1
    end
    return true
  end
end
puts bt.is_complete_tree?


# Convert a binary search tree to a sorted, circular, doubly-linked list, in place.
class BinaryTree
  def listfy
    list = []
    list += left.listfy if left
    list += [element]
    list += right.listfy if right
    list
  end
end
p bt.listfy





